package kz.pompei.ifacer.grot.acts;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import kz.pompei.ifacer.model.widgets.Widget;

public class GrotStorage implements Iterable<Widget> {
  private final List<Widget> widgets = new ArrayList<>();
  
  @Override
  public Iterator<Widget> iterator() {
    return widgets.iterator();
  }
  
  GrotStorage() {}
  
  public void append(Widget widget) {
    widgets.add(widget);
  }
  
  void removeLast() {
    widgets.remove(widgets.size() - 1);
  }
  
  Widget removeByIndex(int index) {
    return widgets.remove(index);
  }
  
  public Widget get(int index) {
    return widgets.get(index);
  }
  
  public int size() {
    return widgets.size();
  }
  
  void insert(int index, Widget widget) {
    widgets.add(index, widget);
  }
  
  public Widget getWidgetByUuid(UUID uuid) {
    for (Widget w : widgets) {
      if (w.uuid.equals(uuid)) return w;
    }
    throw new IllegalArgumentException("No widget with uuid = " + uuid);
  }
  
  public int getIndexByUuid(UUID uuid) {
    int index = 0;
    for (Widget w : widgets) {
      if (w.uuid.equals(uuid)) return index;
      index++;
    }
    throw new IllegalArgumentException("No widget with uuid = " + uuid);
  }
  
  public void clean() {
    widgets.clear();
  }
  
  public void moveToIndex(UUID uuid, int toIndex) {
    int index = getIndexByUuid(uuid);
    if (index == toIndex) return;
    Widget widget = widgets.remove(index);
    widgets.add(toIndex, widget);
  }
}
